package com.heima.hello.controller;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 手机信息发送Controller
 *
 */
@RestController
@RequestMapping("/sms")
public class SMSController {
    /**
     * 发送信息
     *
     * @return 1-信息发送成功
     */
    @RequestMapping("/sendMsg")
    public String sendMsg() {
        // 参考文档：http://www.smschinese.cn/api_java.shtml
        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod("https://utf8api.smschinese.cn/");
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 设置请求报文头转码
        NameValuePair[] data = {new NameValuePair("Uid", "用户名"),
                new NameValuePair("Key", "注册的秘钥"),
                new NameValuePair("smsMob", "手机号"),
                new NameValuePair("smsText", "验证码：8888")};
        post.setRequestBody(data);

        try {
            httpClient.executeMethod(post);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:" + statusCode); //HTTP状态码
        for (Header h : headers) {
            System.out.println(h.toString());
        }
        String result;
        try {
            result = new String(post.getResponseBodyAsString().getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(result);  //打印返回消息状态

        post.releaseConnection();
        return result;
    }
}
